﻿/**
 * @file fwave_pcm_test2.cpp
 * Copyright (c) Gaaagaa. All rights reserved.
 * 
 * @author  : Gaaagaa
 * @date    : 2020-02-18
 * @version : 1.0.0.0
 * @brief   : 播放 wave-pcm 格式的音频文件（测试 fwave_rpcm_t）。
 */

#include "fwave_pcm.h"
#include "audio_dev.h"

#define SDL_main_h_
#include <SDL/SDL.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

////////////////////////////////////////////////////////////////////////////////

int main(int argc, char * argv[])
{
    x_errno_t xerr_no = X_ERR_UNKNOW;
    x_int32_t xit_err = X_ERR_UNKNOW;

    //======================================

    if (argc < 2)
    {
        printf("Usage: \n\t %s < wave-pcm file path >\n", argv[0]);
        return -1;
    }

    SDL_Init(SDL_INIT_AUDIO);

    //======================================

    fwave_rpcm_t fwave_rpcm;
    xerr_no = fwave_rpcm.open(argv[1]);
    if (XERR_FAILED(xerr_no))
    {
        printf("fwave_rpcm.open([%s]) return error code: %s\n",
               argv[1], fwave_rpcm_t::xerrno_name(xerr_no));
        return -1;
    }

    x_uint16_t xut_format = X_AUDIO_S16;
    if (4 == (fwave_rpcm.format().xut_sampbits / 2))
        xut_format = X_AUDIO_S32;
    else if (1 == (fwave_rpcm.format().xut_sampbits / 2))
        xut_format = X_AUDIO_S8;

    //======================================

    adev_playout_t audio_player;
    xit_err = audio_player.open(
                    -1,
                    (x_uint8_t)fwave_rpcm.format().xut_channels,
                    xut_format,
                    fwave_rpcm.format().xut_samprate);
    if (0 != xit_err)
    {
        printf("audio_player.open(-1, [%d], [%d], [%d]) return error code: %d\n",
               fwave_rpcm.format().xut_samprate,
               fwave_rpcm.format().xut_channels,
               xut_format,
               xit_err);
        fwave_rpcm.close();
        return -1;
    }

    //======================================

    const x_uint32_t xut_csize = 16 * 1024;
    x_byte_t xbt_buffer[xut_csize];

    while (X_TRUE)
    {
        if (fwave_rpcm.is_eof())
        {
            if (audio_player.buffer_size() <= 0)
                break;
            SDL_Delay(10);
            continue;
        }

        if (audio_player.buffer_size() <= xut_csize)
        {
            x_fsize_t xst_rbytes = fwave_rpcm.read(xbt_buffer, xut_csize);
            if (xst_rbytes > 0)
            {
                audio_player.playout(xbt_buffer, (x_uint32_t)xst_rbytes);
            }
        }

        SDL_Delay(10);
    }

    //======================================

    audio_player.close();
    fwave_rpcm.close();

    SDL_Quit();

    //======================================

    return 0;
}

